package http;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * 封装http请求的数据
 * 比如 method get/post uri 参数列表等等
 * LMYRequest 作用就等价于原生的servlet 中的HttpServletRequest
 */
public class LmyRequest {

    private String method;

    private String uri;

    private HashMap<String,String> parameters = new HashMap<>();

    private InputStream inputStream = null;

    //构造器
    //inputStream是和对应的http请求的socket关联
    public LmyRequest (InputStream inputStream) {

        //转成字节流
        try {
            this.inputStream = inputStream;
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(this.inputStream, StandardCharsets.UTF_8));
            //读取第一行 请求行
            /*
                GET - /lmyServlet?num1=10&num2=20
             */
            String requestLine = bufferedReader.readLine();
            String[] requestLineArr = requestLine.split(" ");
            //得到method
            this.method = requestLineArr[0];
            //解析得到uri /lmyServlet?num1=10&num2=20
            int index = requestLineArr[1].indexOf("?");
            if (index != -1) {
                //说明有参数列表
                this.uri = requestLineArr[1].substring(0, index);
                //获取参数列表，放入parameters num1=10&num2=20
                String parameters = requestLineArr[1].substring(index + 1);
                //["num1=10"]   ["num2=20"]
                String[] parametersPair = parameters.split("&");
                if (null != parametersPair && !"".equals(parametersPair)) {
                    //再次分割
                    for (String pair : parametersPair) {
                        //["num1","10"]
                        String[] keyValue = pair.split("=");
                        if (keyValue.length == 2) {
                            //放入到 parameters 参数hashmap
                            this.parameters.put(keyValue[0], keyValue[1]);
                        }
                    }
                }
            } else {
                this.uri = requestLineArr[1];
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getParameter(String key) {
        if (parameters.containsKey(key)) {
            return parameters.get(key);
        } else {
            return "";
        }
    }

    @Override
    public String toString() {
        return "LmyRequest{" +
                "method='" + method + '\'' +
                ", uri='" + uri + '\'' +
                ", parameters=" + parameters +
                '}';
    }
}
